#include <allegro.h>
#include <stdio.h>
#include "player.h"
#include "object.h"
#include "song.h"

#define SCR_W 800
#define SCR_H 600
#define MIO_X_SPEED 5

BITMAP* buffer;
BITMAP* note_img;
player* mio;
object* notes[100];
song* musiquinha;
FILE* pstage;

volatile int my_time_while = 0;

void inc_my_time_while() {
	my_time_while++;
}
END_OF_FUNCTION(inc_my_time_while)

void load(char *file_stage){
	char name_musiquinha[50];
	char img_notes[50];
	int n_notes, t_seconds, t_x, t_speed;
	
	pstage = fopen(file_stage, "r");
	if (pstage == NULL)
		return;
	
	fscanf(pstage, "%s", name_musiquinha);
	
	musiquinha = new song(name_musiquinha);
	
	fscanf(pstage, "%s", img_notes);
	
	note_img = load_bitmap(img_notes, NULL);
	
	fscanf(pstage, "%d", &n_notes);
	for (int i = 0; i < n_notes; i ++) {
		fscanf(pstage, "%d %d %d", &t_seconds, &t_x, &t_speed);
		notes[i] = new object(t_seconds, t_x, 0, t_speed, note_img);
	}
	fclose(pstage);
}

void draw_all() {
	acquire_screen();

	clear_to_color(buffer, makecol(255, 255, 255));
	mio->draw(buffer);

	draw_sprite(screen, buffer, 0, 0);

	release_screen();
}

int main() {
	allegro_init();
	
	LOCK_VARIABLE(my_time_while);
	LOCK_FUNCTION(inc_my_time_while);
	
	install_timer();
	install_keyboard();
	install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL);

	set_color_depth(24);

	set_gfx_mode(GFX_AUTODETECT_WINDOWED, SCR_W, SCR_H, 0, 0);

	buffer = create_bitmap(SCR_W, SCR_H);

	int my_time = 0;
	int my_delay = 100;
	
	mio = new player(SCR_W, SCR_H, MIO_X_SPEED, "player.bmp");

	//song music("music.wav");
	//music.play();

	install_int_ex(inc_my_time_while, BPS_TO_TIMER(60));
	while (!key[KEY_ESC]) {
		while (my_time_while){
			mio->move(SCR_W);
			// toda a logica entra aqui
			my_time_while--;
		}
		draw_all();		while (!my_time_while)
			rest(1);
	}

	//music.stop();
	return 0;
}
END_OF_MAIN();

